<template>
  <div>
<!--  ==================流程定义列表===============  -->
    <a-card v-if="!xmlFrame.open||xmlView">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="流程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程分类" prop="category">
        <el-select @change="handleQuery" v-model="queryParams.categoryId" placeholder="请选择流程分类" clearable prop="category">
          <el-option label="请选择" value="" />
          <el-option v-for="category in categorys" :key="category.id" :label="category.name" :value="category.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="激活" prop="useStatus">
        <el-switch
          v-model="queryParams.useStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="handleQuery"
        >
        </el-switch>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增流程定义</el-button>
      </el-form-item>
    </el-form>

      <el-table
        v-loading="loading" fit
        :data="definitionList"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="流程模型编号" align="center" prop="id" />
 
      <el-table-column label="流程标识代号" align="center" prop="key"  />
      <el-table-column label="流程分类" align="center"  prop="categoryName"  > 
      </el-table-column>
      <el-table-column label="流程名称" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="handleReadImage(scope.row.id)">
            <span>{{ scope.row.name }}</span>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.useStatus === 0">草稿</el-tag>
          <el-tag type="warning" v-if="scope.row.useStatus === 1">待发布</el-tag>
          <el-tag type="success" v-if="scope.row.useStatus === 2">已发布</el-tag>
          <el-tag type="warning" v-if="scope.row.useStatus === -1">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-edit-outline" @click.native="handleEdit(scope.row)">
                编辑信息
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-edit-outline" @click.native="handleLoadXml(scope.row)"  v-if="scope.row.useStatus === 0">
                模型设计
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-video-pause" @click.native="publishModel(scope.row)"  v-if="scope.row.useStatus === 0" >
                发布流程
              </el-dropdown-item>
              <!-- <el-dropdown-item icon="el-icon-video-pause" @click.native="handleUpdateSuspensionState(scope.row, 2)"  >
                启用
              </el-dropdown-item> -->
              <el-dropdown-item icon="el-icon-video-play" @click.native="handleUpdateSuspensionState(scope.row, -1)"  >
                禁用
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="handleDelete(scope.row)"  v-if="scope.row.useStatus === 0">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="total>0"
      :total="total"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      @size-change="getList"
      @current-change="getList"
    />
    </a-card>
      <!-- 流程图 -->
    <a-card v-if="xmlFrame.open&&!xmlView" :title="xmlFrame.title">
      <a slot="extra" href="#" @click="()=>{xmlFrame.open=false}">返回</a>
      <bpmn-modeler
        v-if="xmlShow"
        ref="refNode"
        :xml="xmlData"
        :users="users"
        :groups="groups"
        :categorys="categorys"
        :is-view="xmlView"
        @save="save"
      />
    </a-card>
<!--  弹窗预览  -->
      <a-modal :title="xmlFrame.title" :visible.sync="xmlView&&xmlFrame.open" :width="xmlFrame.width"
        :footer="null" closable @cancel="()=>{xmlView=false,xmlFrame.open=false}"
      >
        <bpmn-modeler
          v-if="xmlShow"
          ref="refNode"
          :xml="xmlData"
          :users="users"
          :groups="groups"
          :categorys="categorys"
          :is-view="xmlView"
          @save="save"
        />
      </a-modal>


        <j-modal
    :title="modal.title"
    :width="modal.width"
    :visible="modal.visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': modal.disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">
    <flow-model-form ref="realForm" @ok="submitCallback" :disabled="modal.disableSubmit"></flow-model-form>
  </j-modal>

  </div>
</template>

<script>
import bpmnModeler from "workflow-bpmn-modeler";
import { deleteAction, getAction, postAction,putAction, downFile,getFileAccessHttpUrl } from '@/api/manage'
import {
  categoryList,
  delDeployment,
  listDefinition,
  readXml,
  roleList,
  saveXml,
  updateState,
  userList
} from "@views/flowable/api/definition";
 import FlowModelForm from './FlowModelForm'

export default {
  components: {
    bpmnModeler,
    FlowModelForm,
  },
  data() {
    return {
      /*===================设计器属性======================*/
      users: [],
      groups: [],
      categorys: [],
      modal:{
        title:'',
        width:896,
        visible: false,
        disableSubmit: false
      },
      /*=================页面属性===================*/
      loading: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      definitionList: [],
      allDefinitionList: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        modelName: null,
        categoryId: null,
        categoryName: null,
        useStatus: 1,
        modelKey: null,
        // tenantId: null,
        // deployTime: null,
        // derivedFrom: null,
        // derivedFromRoot: null,
        // parentDeploymentId: null,
        // engineVersion: null
      },
      xmlFrame:{
        width:'70%',
        title:'流程图',
        open: false,
        src: "",
      },
      // xml
      xmlData:"",
      xmlShow: true,
      xmlView: false,
      currentModelData:{},


    };
  },
  created() {
    this.initUserAndRole();
    this.getList();
  },
  methods: {
    /*===============设计器===============*/
    initUserAndRole(){
      userList({}).then(res=>{
        this.users = res.result||[]
        this.users.map(o=>{
          o.id = o.username
          o.name = o.realname
        })
      })
      roleList({}).then(res=>{
        this.groups = res.result||[]
        this.groups.map(o=>{
          o.name = o.roleName
        })
      })
      categoryList({}).then(res=>{
        this.categorys = res.result||[]
      })
    },
    
    handleAdd () {
        this.modal.visible = true;
        this.modal.title = "新增";
        this.modal.disableSubmit = false;
        this.$nextTick(()=> {
          this.$refs.realForm.add();
        })
    },
    handleEdit (record) {
      this.modal.visible=true;
      this.modal.title = "编辑";
      this.modal.disableSubmit = false;
      this.$nextTick(()=>{

        
        getAction( "/flow/model/"+ record.id).then((res) => {
          if (res.success) {
            this.$refs.realForm.edit(res.result);
          } else {
            that.$message.warning("查询数据失败！"+res.message);
          }
        });

        
      })
    },
    close () {
      this.$emit('close');
      this.modal.visible = false;
    },
    handleOk () {
      this.$refs.realForm.submitForm();
    },
    submitCallback(){
      this.$emit('ok');
      this.modal.visible = false;
      this.getList();
    },
    handleCancel () {
      this.close()
    },


    getModelDetail(id) {
      // 发送请求，获取xml
      readXml(id).then(res =>{
        this.xmlData = res.result.xml;
      })
    },
    getCategoryName(category){
      let find = this.categorys.find(o=>o.id==category);
      if (find){
        return find.name
      }
      return ''
    },
    /*保存流程定义*/
    save(data) {
      console.log(data);  // { process: {...}, xml: '...', svg: '...' }
      console.log(this.currentModelData);  // { process: {...}, xml: '...', svg: '...' }
      
      const params = {
        id: this.currentModelData.id, 
        xml: data.xml
      } 
      saveXml(params).then(res => {
        this.$message.success("保存成功")
        // 关闭当前标签页并返回上个页面
        this.getList()
        this.xmlFrame.open = false
      })
    },
    /*================页面===============*/
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.queryParams.suspensionState = this.queryParams.useStatus?1:0;
      this.getList();
    },
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      // 最新版本
      const param1 = Object.assign({
        isLastVersion:1,
      },this.queryParams)
      listDefinition(param1).then(response => {
        this.definitionList = response.result.records;
        this.total = response.result.total;
        this.loading = false;
        for (const definition of this.definitionList) {
          definition.hasChildren = true
        }
      });
      // 所有
      const param2 = Object.assign({
        isLastVersion:0
      },this.queryParams,{
        pageSize: 9999,
        pageIndex:1
      })
      listDefinition(param2).then(response => {
        console.log(response)
        this.allDefinitionList = response.result.records;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /** 打开流程设计弹窗页面 */
    handleLoadXml(row){
      
      if (row&&row.id){
        console.log(row)
        this.currentModelData = row;
        this.handleReadImage(row.id);
        this.xmlView = false
        this.xmlFrame.title = "编辑流程图";
      } else {
        //新增
        this.xmlData = ''
        this.xmlView = false
        this.xmlFrame.open = true
        this.xmlFrame.title = '新增流程'
        this.xmlShow = false
        this.$nextTick(()=>{
          this.xmlShow = true
        })
      }
      this.xmlFrame.width = '90%'
    },
    /** 流程图查看 */
    handleReadImage(id){
      this.xmlFrame.title = "流程图";
      this.xmlFrame.open = true;
      this.xmlFrame.width = '70%';
      // this.xmlFrame.src = process.env.VUE_APP_BASE_API + "/flowable/definition/xmlFrame/" + deploymentId;
      // 发送请求，获取xml
      this.xmlView = true
      readXml(id).then(res =>{
        if (res.success){
           this.xmlShow = true
          this.xmlData = res.result.xml
          /*this.xmlShow = false
          this.$nextTick(()=>{
            this.xmlShow = true
          })*/
        } else {
          this.$message.error("获取流程图失败！")
          
          this.$nextTick(()=>{
             this.xmlShow = false
            this.xmlData = "";
          })

        }
      })
    },
    // 打开业务表单
    handleForm() {
    },
    // 配置业务表单
    handleAddForm(row) {
    },
    /** 挂起/激活流程 */
    handleUpdateSuspensionState(row, status){
       
      const params = {
        id: row.id,
        state: status
      }
      updateState(params).then(res => {
        this.$message.success("更新状态成功");
        this.getList();
      });
    },
    publishModel(row){
       
      const params = {
        modeId: row.id 
      }
      getAction( "/flow/model/publish/"+ row.id, params).then((res) => {
          if (res.success) {
            this.$message.success("发布成功"); 
            this.getList();
          } else {
            this.$message.warning("发布失败！"+res.message);
          }
        });
       
    },

    /** 删除按钮操作 */
    handleDelete(row) { 
      this.$confirm({
        title:"警告",
        content:'是否确认删除流程模型编号为"' + row.id + '"的数据项?',
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        onOk:()=>{
          deleteAction("flow/model/"+ row.id, {id:row.id}).then((res) => {
            this.getList();
            if (res.success){
              this.$message.success('删除成功');
            } else {
              this.$message.success('删除失败');
            }
        });

 
        }
      })
    },
    load(tree, treeNode, resolve) {
      const key = tree.key;
      const childrens = []
      for (const one of this.allDefinitionList) {
        if (one.key==key&&one.id!=tree.id){
          childrens.push(one)
        }
      }
      console.log(tree, treeNode,this.allDefinitionList,childrens)
      resolve(childrens)
    }
  },
  computed: {
    getContainer() {
      return document.querySelector('#app')
    }
  }
};
</script>